package com.digitalchina.lxnsy.activity.old;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessRealTimePrice;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.TopSortVO;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.view.ChannelView.PriceFragmentV2;
import com.digitalchina.lxnsy.viewholder.TopTypeHolder;
import com.digitalchina.lxnsy.xml.ChannelXML;
import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.BaseViewHolder;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.weyye.library.colortrackview.ColorTrackTabLayout;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：顶部有tab切换的
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2017/7/22 19:58
 * 修改备注：
 * ================================================
 */
public class RealTimePriceTabV2Activity extends BaseActivity implements PriceFragmentV2.CallBackValue {

    @Bind(R.id.viewPager)
    ViewPager viewPager;
    @Bind(R.id.tab_tv_update_time)
    TextView tabTvUpdateTime;
    @Bind(R.id.more)
    ImageView more;
    @Bind(R.id.tab2)
    ColorTrackTabLayout tab2;
    @Bind(R.id.more2)
    ImageView more2;
    @Bind(R.id.recyclerView)
    EasyRecyclerView recyclerView;


    private List<TopSortVO> oneList = new ArrayList<>(); // 第1行分类(2级)
    private List<TopSortVO> twoList = new ArrayList<>(); // 第2行分类(3级)
    private List<Fragment> fragments = new ArrayList<>();
    private PriceFragmentV2 priceFragment;
    private MyPagerAdapter adapter;
    private RecyclerArrayAdapter adapterH;
    private String pCode = "";

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_realtime_price_tab_v2);
        setTitle("实时价格");
        setRightText("搜索分类");
    }

    @Override
    public void initMember() {

        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        recyclerView.setAdapter(adapterH = new RecyclerArrayAdapter(this) {
            @Override
            public BaseViewHolder OnCreateViewHolder(ViewGroup parent, int viewType) {
                return new TopTypeHolder(parent);
            }
        });

        adapter = new MyPagerAdapter(getSupportFragmentManager(), fragments, oneList);
        viewPager.setOffscreenPageLimit(3);
        viewPager.setAdapter(adapter);

        tab2.setSelectedTabIndicatorHeight(Utils.dip2px(this, 2));
        //设置每个Tab的内边距
        tab2.setTabPaddingLeftAndRight(20, 20);
        tab2.setupWithViewPager(viewPager);


        String jsonList = ChannelXML.getDefaultType(this);
        if (!StringUtil.isStrEmpty(jsonList))
            oneList = JSON.parseArray(jsonList, TopSortVO.class);
        if (oneList != null && oneList.size() > 0) {
            setOneType();
        } else
            // 获取顶部默认分类
            BusinessRealTimePrice.getTopDefaultType(this, mHandler);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 888) {
            if (resultCode == 999) {
                TopSortVO vo = (TopSortVO) data.getSerializableExtra("selectType");
                pCode = vo.getCode();
                for (int i = 0; i < oneList.size(); i++) {
                    oneList.get(i).setSelect(false);
                    if (vo.getCode().equals(oneList.get(i).getCode()))
                        oneList.remove(i);
                }
                oneList.add(0, vo);
                oneList.get(0).setSelect(true);
                adapterH.clear();
                adapterH.addAll(oneList);
                recyclerView.scrollToPosition(0);
                viewPager.removeAllViews();
                viewPager.removeAllViewsInLayout();
                fragments.clear();
                twoList.clear();
                adapter.setFragmentList(fragments, twoList);
                BusinessRealTimePrice.getTopLevelType(this, pCode, mHandler);
            } else if (resultCode == 998) {
                TopSortVO vo = (TopSortVO) data.getSerializableExtra("selectType");
                for (int i = 0; i < twoList.size(); i++) {
                    if (vo.getCode().equals(twoList.get(i).getCode()))
                        twoList.remove(i);
                }
                twoList.add(1, vo);
                fragments.clear();
                for (int i = 0; i < twoList.size(); i++) {
                    if (i == 7)
                        break;
                    priceFragment = new PriceFragmentV2();
                    fragments.add(priceFragment);
                    Bundle bundle = new Bundle();
                    bundle.putString("code", twoList.get(i).getCode());
                    bundle.putString("pCode", pCode);
                    bundle.putSerializable("twoList", (Serializable) twoList);
                    priceFragment.setArguments(bundle);
                }
                adapter.setFragmentList(fragments, twoList);
                tab2.setCurrentItem(1);
            }

        }

    }

    @Override
    public void addListener() {

        adapterH.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (oneList.get(position).isSelect())
                    return;
                pCode = oneList.get(position).getCode();
                for (int i = 0; i < oneList.size(); i++) {
                    oneList.get(i).setSelect(i == position);
                }
                adapterH.notifyDataSetChanged();

                viewPager.removeAllViews();
                viewPager.removeAllViewsInLayout();
                fragments.clear();
                twoList.clear();
                adapter.setFragmentList(fragments, twoList);
                // 根据返回的第一层type获取第二层type
                if (oneList != null && oneList.size() > 0) {
                    BusinessRealTimePrice.getTopLevelType(RealTimePriceTabV2Activity.this, oneList.get(position).getCode(), mHandler);
                }
            }
        });

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG.MSG_GET_TOP_DEFAULT_TYPE_SUCCESS: // 第一层
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_GET_TOP_LEVEL_TYPE_SUCCESS: // 第二层
                        callBack2(msg.obj);
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {
        oneList = FastJsonUtil.getListBean(object.toString(), "list", TopSortVO.class);
        setOneType();
    }

    private void setOneType() {
        for (int i = 0; i < oneList.size(); i++) {
            oneList.get(i).setSelect(i == 0);
        }

        if (oneList.size() > 0)
            pCode = oneList.get(0).getCode();
        adapterH.addAll(oneList);

        viewPager.removeAllViews();
        viewPager.removeAllViewsInLayout();
        // 根据返回的第一层type获取第二层type
        if (oneList != null && oneList.size() > 0) {
            BusinessRealTimePrice.getTopLevelType(this, oneList.get(0).getCode(), mHandler);
        }
    }

    // 第二层
    private void callBack2(Object object) {
        twoList = FastJsonUtil.getListBean(object.toString(), "list", TopSortVO.class);
        fragments.clear();
        TopSortVO vo = new TopSortVO();
        vo.setName("全部");
        vo.setSelect(true);
        vo.setCode("");
        twoList.add(0, vo);
        for (int i = 0; i < twoList.size(); i++) {
            if (i == 7)
                break;
            priceFragment = new PriceFragmentV2();
            fragments.add(priceFragment);
            Bundle bundle = new Bundle();
            bundle.putString("code", twoList.get(i).getCode());
            bundle.putString("i", String.valueOf(i));
            bundle.putString("pCode", pCode);
            bundle.putSerializable("twoList", (Serializable) twoList);
            priceFragment.setArguments(bundle);
        }
        adapter.setFragmentList(fragments, twoList);
        tab2.setCurrentItem(0);
    }

    @Override
    public void rightOnClick() {
        GotoUtil.gotoForResultActivity(RealTimePriceTabV2Activity.this, RealTimePriceTabSearchActivity.class, 888);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.more, R.id.more2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.more:
                GotoUtil.gotoForResultActivity(RealTimePriceTabV2Activity.this, ChannelV2Activity.class, 888);
                break;
            case R.id.more2:
                GotoUtil.gotoForResultActivity(RealTimePriceTabV2Activity.this, ChannelV2SubclassActivity.class, 888, "pCode", pCode);
                break;
        }
    }

    //要获取的值  就是这个参数的值
    public void SendMessageValue(String strValue) {
        // TODO Auto-generated method stub
        tabTvUpdateTime.setText(strValue);
    }


    private class MyPagerAdapter extends FragmentStatePagerAdapter {
        private List<Fragment> fragments = null;
        private List<TopSortVO> myList = null;

        public MyPagerAdapter(FragmentManager fm, List<Fragment> fragments, List<TopSortVO> myList) {
            super(fm);
            this.fragments = fragments;
            this.myList = myList;
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return myList.get(position).getName();
        }

        public void setFragmentList(List<Fragment> pList, List<TopSortVO> channelEntityList) {
            this.fragments = pList;
            this.myList = channelEntityList;
            notifyDataSetChanged();
        }

        public void addFragment(Fragment fragment, TopSortVO topSortVO) {
            this.fragments.add(1, fragment);
            this.myList.add(1, topSortVO);
            notifyDataSetChanged();
        }

        @Override
        public int getItemPosition(Object object) {
            // 最简单解决 notifyDataSetChanged() 页面不刷新问题的方法
            return POSITION_NONE;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (oneList != null && oneList.size() > 0) {
            int max = oneList.size();
            if (max > 8)
                max = 8;
            String json = JSON.toJSONString(oneList.subList(0, max));
            ChannelXML.setDefaultType(this, json);
        }

    }
}
